package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.OrganizationService;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.MD5Util;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

@Controller
@RequestMapping("/checkRule")
public class CheckRuleController  extends BaseController{
	@Autowired
	private OrganizationService organizationService;
	//查询所有用户
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 and type=0 ";
		if(this.getLoginUser().getSubOrgIds()!=null && !this.getLoginUser().getSubOrgIds().equals("")) {
			where+=" and org_id in ("+this.getLoginUser().getSubOrgIds()+") ";
		}
		
		
		//搜索参数
		String searchVar=null;
		String varValue=null;
		if(request.getParameter("varValue")!=null && !request.getParameter("varValue").toString().trim().equals("")){
			
			if(request.getParameter("searchVar")!=null && !request.getParameter("searchVar").toString().trim().equals("")){
				searchVar=request.getParameter("searchVar");
				if("create_user".equals(searchVar)){
					varValue=request.getParameter("varValue");
					Map record=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.user+" where user=?",new Object[]{varValue});	
					if(record != null){
						where += " and create_user = " + record.get("id");
					}else{
						data.put("data", "");
						return WebUtil.resultString(data,request);
					}
				}else{
					whereParamList.add("%"+request.getParameter("varValue")+"%");
					where += " and "+searchVar+" like ? ";
				}
				
			}else{
				where+=" and name like ? ";
			}
		}
		
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}
		if(request.getParameter("org_name")!=null && !request.getParameter("org_name").toString().trim().equals("")){
			where+=" and org_name like ? ";
			whereParamList.add("%"+request.getParameter("org_name")+"%");
		}
		//用于选择流转规则时排除规则本身
		if(request.getParameter("excludeId")!=null && !request.getParameter("excludeId").toString().trim().equals("")){
			where+=" and id != ? ";
			whereParamList.add(request.getParameter("excludeId"));
		}
		
		//机构筛选条件
		if(request.getParameter("org_id")!=null && StringUtil.isNotNullOrEmpty(request.getParameter("org_id").toString().trim()) && !request.getParameter("org_id").equals("0")){
			/*where+=" and find_in_set(org_id,?) ";
			int org_id = new Integer(request.getParameter("org_id").toString());
			String getOrgIds = organizationService.getOrgIds(org_id);
			whereParamList.add(getOrgIds);*/
			where+=" and org_id=? ";
			whereParamList.add(request.getParameter("org_id"));
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		//为栏目选择审批规则时会带有站点id参数，需要查询出站点对应的机构ID，不允许使用下级机构的审批规则
		if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("")){
			String siteId=request.getParameter("site_id");
			Map site=this.getCommonService().getJdbcDao().queryRow("select org_id from "+DBTable.site+" where id=?", new Object[] {siteId});
			if(site!=null) {
				
				int orgId=Integer.parseInt(site.get("org_id").toString());
				//查找上级机构
				
				String orgIds=organizationService.getParentOrgIds(orgId);
				if(orgIds.equals("")) {
					orgIds=orgId+"";
				}else {
					orgIds=orgId+","+orgIds;
				}
				where+=" and org_id in ("+orgIds+") ";
			}else {
				where+=" and 1=0 ";
			}
			
		}
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="position";
		String sortOrder="desc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		//System.out.println("select * from "+DBTable.checkRule+" "+where+" order by "+sortField+" "+sortOrder+",create_time desc,id desc limit ?,?");
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.checkRule+" "+where+" order by "+sortField+" "+sortOrder+",create_time desc,id desc limit ?,?", whereParamList.toArray());
		//this.getDictionaryService().setDictionaryText(dataList, "publish", this.getDictionaryService().getDictionaryItemList("publishVars"));
		
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
				
				Date updatedate = (Date)row.get("update_time");
				row.put("update_time",sdf.format(updatedate));
				/*//更新人
				if(StringUtil.isNotNullOrEmpty(row.get("update_user")) && !"0".equals(row.get("update_user"))) {
					Map userData=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where id=?",new Object[]{row.get("update_user")});
					if(userData !=null) {
					   row.put("update_user",userData.get("name"));
					}
				}*/
				//节点数
				Map ruleItemCount=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRuleItem+" where check_rule_id=? and del_flag=0",new Object[] {row.get("id")});
				int nodeNums=0;
				if(ruleItemCount.get("count_num")!=null){
					nodeNums=new Integer(ruleItemCount.get("count_num").toString()).intValue();
				}
				row.put("nodeNums",nodeNums);
				//关联栏目数
				int moduleNums=this.getCommonService().getJdbcDao().querySqlForInt("select count(id) from "+DBTable.menu+" where check_rule_id=? and del_flag=0",new Object[] {row.get("id")});
				row.put("moduleNums",moduleNums);
				
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRule+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		return WebUtil.resultString(data,request);
	}
	
	

	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRule+" where id=?",new Object[]{id});	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		return WebUtil.resultString(data,request);
	}
	

	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		//机构org_id
		if(StringUtil.isNullOrEmpty(data.get("org_id"))) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "保存失败，请选择所属机构");
			return WebUtil.resultString(result,request);
		} else {
			int org_id = new Integer(data.get("org_id").toString());
			if(org_id <=0) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "保存失败，请选择所属机构");
				return WebUtil.resultString(result,request);
			}
		}
		
		if(id==null || id.equals("")){
			Date date = new Date();
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				data.put("create_time", sdf.format(date));
				data.put("update_time", sdf.format(date));
			}
			data.put("create_user", this.getLoginUserId());
			data.put("update_user", this.getLoginUserId());
			data.put("position", date.getTime());
			this.getCommonService().getJdbcDao().addObj(DBTable.checkRule, data);
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			data.put("update_time", sdf.format(date));
			data.put("update_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().updateObj(DBTable.checkRule, data, "id");
		}
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}

	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set del_flag=1 where id in ("+tmpVar+")",idArray);
	        
	        //删除审批规则时同步清除绑定的栏目数据
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.menu+" set check_rule_id=0,check_rule_name='' where check_rule_id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	//更新发布状态
	@RequestMapping(value="/updatePublish",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePublish(HttpServletRequest request){
		String num = "1".equals(request.getParameter("publish"))?"0":"1";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set publish=? where id=?",new Object[]{num,request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}

	@RequestMapping(value="/upAutoPosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String upAutoPosition(HttpServletRequest request){
		
		String id=request.getParameter("id");
		
		//查询当前新闻
		Map thisNews=this.getCommonService().getJdbcDao().queryRow("select id,position from "+DBTable.checkRule+" where id=?", new Object[] {id});
		
		//查询上一条新闻
		Map prevNews=this.getCommonService().getJdbcDao().queryRow("select id,position from "+DBTable.checkRule+" where position>=? and id!=? and del_flag=0 order by position asc limit 0,1", new Object[] {thisNews.get("position"),id});
		
		
		if(prevNews!=null) {
			//如果两条数据的排序位置相差超过2，则交换并且减1，以避免有排序号重复的数据
			if(Long.parseLong(prevNews.get("position").toString())-Long.parseLong(thisNews.get("position").toString())>2) {
				
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(prevNews.get("position").toString())-1,thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString())+1,prevNews.get("id")});
				
				
			}else {//否则交换排序号
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(prevNews.get("position").toString()),thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString()),prevNews.get("id")});
				
			}
		}
		
		
	
		
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/downAutoPosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String downAutoPosition(HttpServletRequest request){
		String id=request.getParameter("id");
		
		//查询当前新闻
		Map thisNews=this.getCommonService().getJdbcDao().queryRow("select id,position from "+DBTable.checkRule+" where id=?", new Object[] {id});
		
		//查询上一条新闻
		Map nextNews=this.getCommonService().getJdbcDao().queryRow("select id,position from "+DBTable.checkRule+" where position<=? and id!=? and del_flag=0 order by position desc limit 0,1", new Object[] {thisNews.get("position"),id});
		
		
		if(nextNews!=null) {
			//如果两条数据的排序位置相差超过2，则交换并且减1，以避免有排序号重复的数据
			if(Long.parseLong(thisNews.get("position").toString())-Long.parseLong(nextNews.get("position").toString())>2) {
				
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(nextNews.get("position").toString())+1,thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString())-1,nextNews.get("id")});
				
				
			}else {//否则交换排序号
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(nextNews.get("position").toString()),thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRule+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString()),nextNews.get("id")});
				
			}
		}
		
		
	
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
		
	
}
